import React, { FC, useState } from 'react'
import { produce } from 'immer'

const ImmerDemo: FC = () => {
  const [userInfo, setUserInfo] = useState({ name: '李子一', age: 20 })

  function changeAge() {
    console.log(userInfo)
    /* // 不可变数据，不去修改 state 的值，而是传入一个新的值
    setUserInfo({
      ...userInfo,
      age: 21,
    }) */
    setUserInfo(
      produce(draft => {
        draft.age = 21
      })
    )
  }

  const [list, setList] = useState(['x', 'y'])
  function addItem() {
    /* setList([...list, 'z']) */
    setList(
      produce(draft => {
        console.log(draft)
        draft.push('z')
      })
    )
  }

  return (
    <>
      <h2>state 不可变数据</h2>
      <div>{JSON.stringify(userInfo)}</div>
      <button onClick={changeAge}>change age</button>
      <div>{JSON.stringify(list)}</div>
      <button onClick={addItem}>add item</button>
    </>
  )
}

export default ImmerDemo
